<?php

namespace backend\models;

use backend\behaviors\SearchBehavior;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Category;

/**
 * CategorySearch represents the model behind the search form about `common\models\Category`.
 */
class CategorySearch extends Category
{

  public $created_at_start;
  public $created_at_end;
  /**
   * @inheritdoc
   */
  public function attributeLabels()
  {
    return array_merge(
      parent::attributeLabels(),
      [
        'created_at_start' => '开始时间',
        'created_at_end' => '结束时间',
      ]
    );
  }
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'p_id', 'created_at', 'updated_at', 'deleted'], 'integer'],
            [['title','created_at_start','created_at_end'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

  /**
   * @param array() $params
   * @param int $pageSize
   * @param int $f 0|1
   * @return ActiveDataProvider
   */
  public function search($params,$pageSize = 20,$f = 0)
  {
      $query = Category::find($f);

      // add conditions that should always apply here
      $dataProvider = new ActiveDataProvider([
          'query' => &$query,
          'pagination' => ['pageSize'=>$pageSize],
          'sort'=>[
              'defaultOrder'=>[
                  'id'=> SORT_DESC,
              ],
          ],
      ]);
      $this->load($params);
      if (!$this->validate()) {
          // uncomment the following line if you do not want to return any records when validation fails
          // $query->where('0=1');
          return $dataProvider;
      }
      // grid filtering conditions
      $query->andFilterWhere([
          $this->a.'.id' => $this->id,
          $this->a.'.p_id' => $this->p_id,
//            'created_at' => $this->created_at,
//            'updated_at' => $this->updated_at,
//            'deleted' => $this->deleted,
      ]);
      $query->andFilterWhere(['like', $this->a.'.title', $this->title]);

      if(!empty($this->created_at_start) && !empty($this->created_at_end)){
        $query->andFilterWhere(['between', $this->a.'.created_at', strtotime($this->created_at_start),strtotime($this->created_at_end)]);
      }
    return $dataProvider;
  }
}
